package org.jf.tool.fx.jftoolfx.main.controller;

import javafx.concurrent.Worker;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import org.jf.tool.fx.jftoolfx.common.BaseController;

import java.net.URL;
import java.util.ResourceBundle;

/**
 * @author jifeng_zhang
 * @date 2025/8/19 下午1:46
 */
public class HomeController extends BaseController {
    @FXML
    public WebView tianqiWebView;
    @FXML
    public WebView htmlWebView;

    @Override
    protected void init(URL url, ResourceBundle resourceBundle) {
        // 加载初始网页
        WebEngine tianqiEngine = tianqiWebView.getEngine();
        // 设置为常见浏览器的用户代理
        tianqiEngine.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
        tianqiEngine.setJavaScriptEnabled(true);
        tianqiEngine.load("https://i.tianqi.com/?c=code&a=getcode&id=2&num=6&icon=1");
        //engine.load("https://i.tianqi.com/?c=code&id=2&bgc=%23&icon=1&num=6&site=12&lang=cn");

        // 加载初始网页
        WebEngine htmlEngine = htmlWebView.getEngine();
        htmlEngine.setJavaScriptEnabled(true);
        // 设置alert处理器
        htmlEngine.setOnAlert(event -> {
            String message = event.getData();
            System.out.println("Alert: " + message); // 控制台输出

            // 显示JavaFX警告对话框
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("网页提示");
            alert.setHeaderText(null);
            alert.setContentText(message);
            alert.showAndWait();
        });

        htmlEngine.setOnError(event -> {
            System.out.println("WebView Error: " + event.getMessage());
        });

        htmlEngine.getLoadWorker().exceptionProperty().addListener((obs, old, newVal) -> {
            if (newVal != null) {
                newVal.printStackTrace();
            }
        });

        // 加载本地HTML文件
        htmlEngine.load(getClass().getResource("/html/test.html").toExternalForm());

    }
}
